package com.cmcc.linlaker.ui.query.fragment;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.FileProvider;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.cmcc.linlaker.R;
import com.cmcc.linlaker.bean.BaseBean;
import com.cmcc.linlaker.bean.ImageUploadBean;
import com.cmcc.linlaker.crop.ClipImageActivity;
import com.cmcc.linlaker.crop.util.ActivityResultHelper;
import com.cmcc.linlaker.http.ApiDefine;
import com.cmcc.linlaker.ui.query.ImageScanActivity;
import com.cmcc.linlaker.ui.query.ModifyAddressActivity;
import com.cmcc.linlaker.ui.query.ProjectDetailActivity;
import com.cmcc.linlaker.ui.query.bean.ModifyAddressBean;
import com.cmcc.linlaker.ui.query.bean.QueryProjectBean;
import com.cmcc.linlaker.ui.upload.adapter.ImageAdapter;
import com.cmcc.linlaker.ui.upload.bean.ImageBean;
import com.cmcc.linlaker.utils.DensityUtil;
import com.cmcc.linlaker.utils.DictUtils;
import com.cmcc.linlaker.utils.PhotoUtils;
import com.cmcc.linlaker.utils.PictureUtil;
import com.cmcc.linlaker.utils.SPHelper;
import com.cmcc.linlaker.utils.ToastUtils;
import com.cmcc.linlaker.utils.Utils;
import com.cmcc.linlaker.view.ExitDialog;
import com.cmcc.linlaker.view.GridSpacingItemDecoration;
import com.cmcc.linlaker.volley.GsonRequestHelper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

public class ProjectBaseDetailFragment extends Fragment {
    private View fragmentView;

    public static ProjectBaseDetailFragment newInstance() {
        ProjectBaseDetailFragment fragment = new ProjectBaseDetailFragment();
        Bundle bundle = new Bundle();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        fragmentView = inflater.inflate(R.layout.fragment_query_project_base, container, false);
        initView();
        return fragmentView;
    }

    private TextView text_modify_address;
    private TextView text_title, text_pro_code, textDJFM, textBARQ, textXMLX, textJSXZ,
            textXMZT, textAddress, textSYSX, textSSHY, textSSQY, textStartTime, textFinishTime, textIsBH,
            textIsGK, textZYD, textXZJSYD, textZJZMJ, textDSJZMJ, textXMZTZE, textJSGMNR, textJYFW,
            textIsZZXM, textCZFS;

    private ImageAdapter adapter;
    private ArrayList<ImageBean> imageList = new ArrayList<>();
    private RecyclerView recycler_pic;

    private void initView() {
        recycler_pic = fragmentView.findViewById(R.id.recycler_pic);
        setRecyclerView(recycler_pic, imageList);

        text_modify_address = fragmentView.findViewById(R.id.text_modify_address);
        text_modify_address.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                addressBean.address = "";
                addressBean.latitude = 0;
                addressBean.longitude = 0;

                Intent intent = new Intent(getActivity(), ModifyAddressActivity.class);
                intent.putExtra("address", ((ProjectDetailActivity) getActivity()).projectDetailData.address);
                startActivityForResult(intent, 1000);
            }
        });
        text_title = fragmentView.findViewById(R.id.text_title);
        text_pro_code = fragmentView.findViewById(R.id.text_pro_code);
        textDJFM = fragmentView.findViewById(R.id.textDJFM);
        textBARQ = fragmentView.findViewById(R.id.textBARQ);
        textXMLX = fragmentView.findViewById(R.id.textXMLX);
        textJSXZ = fragmentView.findViewById(R.id.textJSXZ);
        textXMZT = fragmentView.findViewById(R.id.textXMZT);
        textAddress = fragmentView.findViewById(R.id.textAddress);
        textSYSX = fragmentView.findViewById(R.id.textSYSX);
        textSSHY = fragmentView.findViewById(R.id.textSSHY);
        textSSQY = fragmentView.findViewById(R.id.textSSQY);
        textStartTime = fragmentView.findViewById(R.id.textStartTime);
        textFinishTime = fragmentView.findViewById(R.id.textFinishTime);
        textIsBH = fragmentView.findViewById(R.id.textIsBH);
        textIsGK = fragmentView.findViewById(R.id.textIsGK);
        textZYD = fragmentView.findViewById(R.id.textZYD);
        textXZJSYD = fragmentView.findViewById(R.id.textXZJSYD);
        textZJZMJ = fragmentView.findViewById(R.id.textZJZMJ);
        textDSJZMJ = fragmentView.findViewById(R.id.textDSJZMJ);
        textXMZTZE = fragmentView.findViewById(R.id.textXMZTZE);
        textJSGMNR = fragmentView.findViewById(R.id.textJSGMNR);
        textJYFW = fragmentView.findViewById(R.id.textJYFW);
        textIsZZXM = fragmentView.findViewById(R.id.textIsZZXM);
        textCZFS = fragmentView.findViewById(R.id.textCZFS);

        setData();
    }

    public static ModifyAddressBean addressBean = new ModifyAddressBean();
    public static boolean isModifyAddress = false;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == getActivity().RESULT_OK) {
            if (requestCode == RC_TAKE_PHOTO) {
                gotoClipActivity(Uri.fromFile(fileUri));
            } else if (requestCode == RC_CHOOSE_PHOTO) {
                gotoClipActivity(data.getData());
            }
        } else if (resultCode == 1000) {
            textAddress.setText(addressBean.address);
            modifyAddress();
        }
    }

    /**
     * 打开截图界面
     */
    public void gotoClipActivity(Uri uri) {
        if (uri == null) {
            return;
        }

        ClipImageActivity.goToClipActivity(getActivity(), uri, new ActivityResultHelper.Callback() {
            @Override
            public void onActivityResult(int resultCode, Intent intent) {
                if (intent == null) {
                    return;
                }

                final Uri uri = intent.getData();
                if (uri == null) {
                    return;
                }
                Bitmap myBitmap = PhotoUtils.getBitmapFromUri(uri, getActivity());

                String fileName = PictureUtil.getCharacterAndNumber();
                File file = new File(PictureUtil.PHOTO_DIR, fileName + ".png");
                PictureUtil.saveMyBitmap(myBitmap, file);

                addBmp(myBitmap);

                uploadPic(fileName + ".png", file);
            }
        });
    }

    private void uploadPic(String fileName, File file) {
        Map<String, String> headers = new HashMap<>();
        headers.put("authToken", SPHelper.getAuthToken());
        headers.put("from", "android");
        OkHttpUtils.post()
                .headers(headers)
                .addFile("file", fileName, file)
                .url(ApiDefine.UPLOAD_PIC)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("onError:", "onError");
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("url:", response);
                        String jsonStr = response;
                        Gson gson = new GsonBuilder().create();
                        ImageUploadBean bean = gson.fromJson(jsonStr, new TypeToken<ImageUploadBean>() {
                        }.getType());

                        if (bean != null) {
                            String imageUrl = getImageListStr(bean);
                        }

                    }
                });
    }


    private void modifyAddress() {
        GsonRequestHelper helper = new GsonRequestHelper(getContext());
        String getUrl = ApiDefine.PROJECT_EDIT;
        Map<String, String> params = new HashMap<>();
        if (addressBean.longitude == 0 || addressBean.latitude == 0) {
            params.put("latitude", ((ProjectDetailActivity) getActivity()).projectDetailData.latitude);
            params.put("longitude", ((ProjectDetailActivity) getActivity()).projectDetailData.longitude);
        } else {
            params.put("latitude", Utils.formatLatLng((float) (addressBean.latitude / 1E6)));
            params.put("longitude", Utils.formatLatLng((float) (addressBean.longitude / 1E6)));
        }

        params.put("address", addressBean.address);
        params.put("id", ((ProjectDetailActivity) getActivity()).projectDetailData.id);
        helper.sendPOSTRequest(getUrl, BaseBean.class, params, true, null);
        helper.setOnResponseListener(new GsonRequestHelper.OnResponseListener() {
            @Override
            public void onError(VolleyError error) {

            }

            @Override
            public void onSuccess(Object data) {
                if (data != null) {
                    BaseBean bean = (BaseBean) data;
                    if (bean.code.equals("0")) {
                        isModifyAddress = true;
                        ToastUtils.showText(getActivity(), "地址已修正");
                    } else {
                        ToastUtils.showText(getActivity(), bean.msg);
                    }
                }
            }
        });
    }

    private void setRecyclerView(final RecyclerView recycler_view, final ArrayList<ImageBean> itemList) {
        recycler_view.setHasFixedSize(true);
        recycler_view.setLayoutManager(new GridLayoutManager(getActivity(), 4));

        recycler_view.setNestedScrollingEnabled(false);
        recycler_view.addItemDecoration(new GridSpacingItemDecoration(4, DensityUtil.dip2px(getActivity(), 10), true));
        adapter = new ImageAdapter(getActivity(), itemList);
        adapter.setOnItemClickListener(new ImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                if (itemList.get(position).type == 0) {
                    selectPictures();
                } else {
                    Intent intent = new Intent(getActivity(), ImageScanActivity.class);
                    intent.putExtra("imageBeanList", imageList);
                    intent.putExtra("position", position);
                    startActivity(intent);
                }
            }

            @Override
            public void onItemDeleteClick(int position) {
                deletePic(position);
            }
        });

        recycler_view.setAdapter(adapter);
    }


    /**
     * 选择图片
     */
    public void selectPictures() {
        showSelectDialog();
    }

    private void showSelectDialog() {
        final String[] items = {"相机", "相册"};
        AlertDialog.Builder builder = new AlertDialog.Builder(
                getActivity());
        builder.setTitle("选择图片")
                .setItems(items, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        if (which == 0) {// 相机
                            takePhoto();
                        } else if (which == 1) {// 相册
                            choosePhoto();
                        }

                    }
                }).create().show();
    }

    public static final int RC_TAKE_PHOTO = 1;
    public static final int RC_CHOOSE_PHOTO = 2;

    private File fileUri = new File(Environment.getExternalStorageDirectory().getPath() + "/lh_photo.jpg");
    private Uri imageUri;

    /**
     * 拍照
     */
    private void takePhoto() {
        imageUri = Uri.fromFile(fileUri);
        //通过FileProvider创建一个content类型的Uri
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            imageUri = FileProvider.getUriForFile(getActivity(), "com.cmcc.linlaker.fileprovider", fileUri);
        }

        PhotoUtils.fragmentTakePicture(this, imageUri, RC_TAKE_PHOTO);
    }

    /**
     * 打开相册
     */
    private void choosePhoto() {
        PhotoUtils.fragmentOpenPic(this, RC_CHOOSE_PHOTO);
    }

    /**
     * 获取图片url
     */
    private String getImageListStr(ImageUploadBean bean) {
        JSONArray jsonArray = new JSONArray();

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("groupName", bean.groupName);
            jsonObject.put("extName", bean.extName);
            jsonObject.put("fileName", bean.fileName);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        jsonArray.put(jsonObject);

        return jsonArray.toString();
    }


    /**
     * 删除图片
     */
    private void deletePic(final int position) {
        ExitDialog dialog = new ExitDialog(getActivity(), R.style.dialog);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setOnConfirmClickListener(new ExitDialog.OnConfirmClickListener() {
            @Override
            public void onConfirmClick() {
                imageList.remove(position);

                adapter.notifyDataSetChanged();
            }
        });
        dialog.show();

        dialog.setContent("确认删除该图片吗？");
        dialog.setConfirmText("删除");
    }

    /**
     * 添加按钮
     */
    private void addButton() {
        ImageBean bean = new ImageBean();
        bean.type = 0;
        imageList.add(bean);

        adapter.notifyDataSetChanged();
    }

    /**
     * 添加图片
     */
    private void addBmp(Bitmap bmp) {
        ImageBean bean = new ImageBean();
        bean.bitmap = bmp;
        bean.type = 1;
        imageList.add(imageList.size() - 1, bean);

        adapter.notifyDataSetChanged();
    }


    private void setData() {
        if (((ProjectDetailActivity) getActivity()).projectDetailData != null) {
            QueryProjectBean.QueryProjectData projectData = ((ProjectDetailActivity) getActivity()).projectDetailData;
            text_title.setText(projectData.name);
            text_pro_code.setText(projectData.code);
            textDJFM.setText(projectData.registerTime);
            textBARQ.setText(projectData.filiTime);
            textXMLX.setText(DictUtils.getType(projectData.type));
            textJSXZ.setText(DictUtils.getNature(projectData.nature));
            textXMZT.setText(DictUtils.getState(projectData.states));
            textAddress.setText(projectData.address);
            textSYSX.setText(DictUtils.getUsingAttributes(projectData.usingAttributes));
            textSSHY.setText(DictUtils.getIndustry(projectData.industry));
            textSSQY.setText(DictUtils.getRegion(projectData.region));
            textStartTime.setText(projectData.startTime);
            textFinishTime.setText(projectData.finishTime);
            textIsBH.setText(DictUtils.getIs(projectData.isProtected));
            textIsGK.setText(DictUtils.getIs(projectData.isControl));
            textZYD.setText(projectData.totalLand);
            textXZJSYD.setText(projectData.addLand);
            textZJZMJ.setText(projectData.totalBuildingArea);
            textDSJZMJ.setText(projectData.aboveBuildingArea);
            textXMZTZE.setText(projectData.investment);
            textJSGMNR.setText(projectData.buildingContent);
            textJYFW.setText(projectData.businessScope);
            textIsZZXM.setText(DictUtils.getIs(projectData.isRemediation));
            textCZFS.setText(projectData.disposalMethod);

            List<ImageBean> urlList = parseFile(projectData.projectFiles);
            imageList.clear();
            imageList.addAll(urlList);
            addButton();
            adapter.notifyDataSetChanged();

            if (urlList.size() > 0) {
                fragmentView.findViewById(R.id.text_no_photo).setVisibility(View.GONE);
                recycler_pic.setVisibility(View.VISIBLE);
            } else {
                recycler_pic.setVisibility(View.GONE);
                fragmentView.findViewById(R.id.text_no_photo).setVisibility(View.VISIBLE);
            }
        }
    }

    private List<ImageBean> parseFile(List<QueryProjectBean.ProjectFileData> projectFiles) {
        List<ImageBean> urlList = new ArrayList<>();

        for (int i = 0; i < projectFiles.size(); i++) {
            QueryProjectBean.ProjectFileData data = projectFiles.get(i);
            String url = data.fastDfsServer + data.groupName + "/" + data.fileName;

            ImageBean bean = new ImageBean();
            bean.path = url;
            bean.type = 1;

            urlList.add(bean);
        }

        return urlList;
    }
}
